from distutils.command.clean import clean
from time import sleep
from zlib import decompress
from threading import Thread
from socket import (SO_RCVLOWAT, socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST)
#from tkinter import PhotoImage, Tk, Canvas, BOTH, Label, YES
from PIL.Image import *
import tkinter as tk
from PIL import ImageTk
import re

obj = re.compile(r'(?P<data>\d+)', re.S)

root = tk.Tk()
root.title('屏幕广播接收')
root.geometry('1280x800+0+0')
# root.overrideredirect(True)

#root.attributes('-topmost', True)

# 使用Lable显示图像
lbImage = tk.Label(root)
lbImage.pack(fill=tk.BOTH, expand=tk.YES)

BUFFER_SIZE = 1400
data = b''

def shwo_image(image_bytes, image_size):
    # 窗口尺寸大小
    screen_width = root.winfo_width()
    screen_height = root.winfo_height()

    global im
    # 重建图像，如果接收的数据不完整，就丢弃
    try:
        im = frombytes('RGBA', image_size, image_bytes)
    except:
        return 
    
    im = im.resize((screen_width, screen_height))
    im = ImageTk.PhotoImage(im)
    lbImage['image'] = im
    lbImage.image = im

def recv_image():
    global receiving, im
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(('', 22222))

    while receiving:
        # 等待接收开始的标志
        while receiving:
            chunk, _ = sock.recvfrom(BUFFER_SIZE)
            # 收到开始标志
            if chunk == b'start':
                print("Start receiving")
                break
            elif chunk == b'close':
                sleep(0.1)
        else:
            break
            
        while receiving:
            # 开始接收图像数据
            chunk, _ = sock.recvfrom(BUFFER_SIZE)
            global data
            if chunk.startswith(b'_over'):
                print("Receive stop")
                strChunk = str(chunk)
                #w = strChunk[8:13] 
                reData = obj.finditer(strChunk)
                size = []
                for it in reData:
                    size.append(int(it.group('data')))
               
                size = tuple(size)
                print(size)
                image_size = size             #(2880, 1800)#eval(chunk[5:]) // 从发送方获取图片大小

                try:
                    image_data = decompress(data)
                except:
                    break
                finally:
                    data = b''
                thread_show = Thread(target=shwo_image, args=(image_data, image_size))
                thread_show.daemon = True
                thread_show.start()
                break
            elif chunk == b'close':
                sleep(0.1)
            data += chunk
            #data.append(chunk)

receiving = True
thread_sender = Thread(target=recv_image)
thread_sender.daemon = True
thread_sender.start()

def close_window():
    global receiving
    receiving = False
    sleep(0.3)
    root.destroy()

root.protocol('WM_DELETE_WINDOW', close_window)

root.mainloop()


